<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class conflict extends CI_Controller {
	var $data;
	public function __construct()
	{
		parent::__construct();		
		$this->load->library('session');
		$this->load->library('pagination');
		$data['title'] = "Conflict";		
		$this->load->model('model_companies');
		$this->load->model('model_conflict');
		$this->load->model('model_customer');
		$this->load->model('model_user');
		$this->load->model('model_feeds');

		// CHECK LOGIN
		$check = $this->session->userdata('login');
		if($check==false){
			redirect(base_url().'login/', 'refresh');
			return;
		}
	}
	
	public function index()
	{
		$this->view();
	}

	public function view($paging=0){
		$is_account = false;
		$per = $this->session->userdata('user_info');
		//print_r($per);
		$my_permisstion = $per["permission_apps"]["AM_SALE_SUPPORT"];
		if(isset($my_permisstion["user_type"])&&count($my_permisstion)>0&&$my_permisstion!=""){
			foreach($my_permisstion["user_type"] as $key => $v){
				if(strtoupper($key)=="IS_ACCOUNT"&&$v==1){							
					$is_account =true;														
				}
			}
		}
			
		if($is_account){
			$this->list_companies($paging);
		}else{
			$this->list_customer($paging);
		}
		
	}


	public function list_customer($paging=0){
	
		if($paging<0){
			$paging=0;
		}

		$array_parent_id = $this->session->userdata('parentId');

		if(isset($_REQUEST["where"])&&$_REQUEST["where"]!=""){
			$where	=$_REQUEST["where"];
		}else{
			$where	='';
		}

		$order_by="cust_create_time ASC";

		$result = $this->model_conflict->selectConflictTemp(array("where"=>$where,"order_by"=>$order_by,"uId"=>$array_parent_id,'limit'=>10,'paging'=>$paging));
		$cust_conflict_id = array();
		foreach($result as $val){
			$cust_conflict_id[] = $val["cust_id"];
		}
		
		$this->data["result"] 	= $this->model_conflict->selectConflict(array("where"=>$where,"order_by"=>$order_by,"cust_conflict_id"=>$cust_conflict_id,'limit'=>10,'paging'=>$paging));
		
		$result_count	= $this->model_conflict->selectConflict(array("where"=>$where,"order_by"=>$order_by,"cust_conflict_id"=>$cust_conflict_id));			
		 $this->data["count_page"] = count($result_count);
		//print_r($this->data);

		//$this->data["set_page"] 	= 'conflict_customer_list';
		//$this->load->view('conflict', $this->data);
        $this->load->view('qt/conflict_list', $this->data);
	}


	public function review(){
		$is_account = false;
		$per = $this->session->userdata('user_info');
			//print_r($per);
			$my_permisstion = $per["permission_apps"]["AM_SALE_SUPPORT"];
				if(isset($my_permisstion["user_type"])&&count($my_permisstion)>0&&$my_permisstion!=""){
					foreach($my_permisstion["user_type"] as $key => $v){
						if(strtoupper($key)=="IS_ACCOUNT"&&$v==1){							
							$is_account =true;														
						}
					}
				}
			
		if($is_account){
		//if($this->fclass->check_permission('special','is_accounting',$this->session->userdata('permissions2'),$this->session->userdata('permissions_base'))==true){
			$this->reviewCompanies();
		}else{

			$this->reviewCustomer();
		}
	}


	function reviewCustomer(){
		/*
		$id = $this->input->get("id");
		$result = $this->model_conflict->selectConflict(array("id"=>$id));
		if(count($result)>0){
			$this->data["result"] = $result[0];
			$uId = $this->data["result"]["uId"];
			$cust_id = $this->data["result"]["cust_id"];

			$this->data["result_detail_sale"] = $this->model_user->selectDetailId(array("uId"=>$uId));
			$result_cust = $this->model_customer->selectIdDetail(array("cust_id"=>$cust_id));

			$my_permisstion = $this->model_user->selectPermitionApp(array("app_id"=>2,"user_id"=>$uId));
			$my_permisstion = json_decode($my_permisstion["permissions"],true);
		//	print_r($my_permisstion );
			$email = $result_cust["cust_email"];
			$phone = $result_cust["cust_phone"];
			$cmnd 	= $result_cust["cust_cmnd"];
			$tax_code = $result_cust["cust_tax_code"];
			$result_list_sale = $this->model_customer->checkExistsJoin(array("cust_email"=>$email,"cust_phone"=>$phone,"cust_cmnd"=>$cmnd,"cust_tax_code"=>$tax_code));

			$array = array();

			foreach($result_list_sale as $val ){

				$rs = $this->model_user->selectPermitionApp(array("app_id"=>2,"user_id"=>$val["uId"]));

				//print_r($rs);
				//echo $val["uId"];
				if(count($rs)>0){
					$permissions = json_decode($rs["permissions"]);
					foreach($permissions->business as $k => $vl){
						foreach($my_permisstion["business"]  as $ke => $value){
							if($k == $ke&&$value=="on"&&$vl=="on"&&strtoupper($ke)=="LED"){
								//if($row["cust_conflict_id"]!=""){									
									$array[] = $val;
								//}
							}
						}
					}
				}
				
			}


		// /	print_r($array);

			$this->data["result_list_sale"] = $array;
			$this->load->view("conflict_detail_view");
		}else{
			$this->load->view('404');
		}
		*/
	
		if(isset($_REQUEST['id'])&&$_REQUEST['id']!=""){	
		
			$paging=@$_GET["per_page"];
			if($paging<0){
					$paging=0;
				}

			$array_parent_id = $this->session->userdata('parentId');
			$cust_id=$_REQUEST['id'];
	
			$result_conflict = $this->model_customer->selectDetail(array("cust_creator_id"=>$this->session->userdata('uId'),"array_uId"=>$array_parent_id,'cust_id'=>$cust_id));			
	

			if(count($result_conflict)>0){

			//echo $this->db->last_query();
			//print_r($result_conflict);
				if($result_conflict[0]["cust_status"]==-2){
					
					$this->data["result_conflict"]=$result_conflict[0];	
					// Lấy khách công ty khách hàng chình 
					$result = $this->model_companies->selectToCustID(array('cust_id'=>$cust_id));
					//echo $this->db->last_query();
					$this->data["result_conflict_comp"]=$result;	
						//print_r($result);
					$user = file_get_contents("http://localhost/ht/hrm/api/search_user_by_app?token=".$this->session->userdata('user_token')."&user_id=".$this->data["result_conflict"]["cust_creator_id"]."&app_name=AM_SALE_SUPPORT");
					$result = json_decode($user,true);
					if($result["result"]==false){
						$this->session->sess_destroy();		
						redirect($this->data["system_url"]."?redirect=http://crm.altamedia.vn", 'refresh');	
						exit();
					}
					//print_r($result);
				//	$result = $this->model_user->selectDetailId(array('uId'=>$this->data["result_conflict"]["cust_creator_id"]));
					//echo $this->db->last_query();
					if(count($result["users"])<=0){
						$this->load->view('404');
						return;
					}
					$this->data["result_conflict_user"]=$result["users"][0];	


					

					if(!isset($_GET["cust_conflict"])){
						$paging=0;
					}

					$this->data["feed_conflict_result"] = $this->model_feeds->select(array('cust_id'=>$cust_id,"limit"=>10,"paging"=>$paging));
					$this->data["feed_conflict_count_page"] = $this->model_feeds->selectCount(array('cust_id'=>$cust_id));



					// khách hàng chính
					$cust_id = $result_conflict[0]["cust_conflict_id"];
					$result = $this->model_customer->selectDetail(array("cust_creator_id"=>$this->session->userdata('uId'),"array_uId"=>$array_parent_id,'cust_id'=>$cust_id));	
					$this->data["result"]=$result[0];	

					$result = $this->model_companies->selectToCustID(array('cust_id'=>$cust_id));
					$this->data["result_comp"]=$result;	

					//$result = $this->model_user->selectDetailId(array('uId'=>$this->data["result"]["cust_creator_id"]));
					$user = file_get_contents("http://localhost/ht/hrm/api/search_user_by_app?token=".$this->session->userdata('user_token')."&user_id=".$this->data["result"]["cust_creator_id"]."&app_name=AM_SALE_SUPPORT");
					$result = json_decode($user,true);
					if($result["result"]==false){
						$this->session->sess_destroy();		
						redirect($this->data["system_url"]."?redirect=http://crm.altamedia.vn", 'refresh');	
						exit();
					}
					
					
					$this->data["result_user"]=$result["users"][0];


					if(!isset($_GET["cust"])){
						$paging=0;
					}

					$this->data["feed_result"] = $this->model_feeds->select(array('cust_id'=>$cust_id,"limit"=>10,"paging"=>$paging));
					$this->data["feed_count_page"] = $this->model_feeds->selectCount(array('cust_id'=>$cust_id));



					
					//$this->data["set_page"] 	= 'conflict_customer_review';
					//$this->load->view('conflict', $this->data);
                    $this->load->view('qt/conflict_customer_review', $this->data);
				}else{
						
					$this->load->view('404');
				}
			}else{
			
				$this->load->view('404');
			}
		}else{
			$this->load->view('404');
		}
		
	}

	function reviewCompanies(){
		if(isset($_REQUEST['id'])&&$_REQUEST['id']!=""){	
			$paging=@$_GET["per_page"];
			if($paging<0){
						$paging=0;
					}

			$cust_id=$_REQUEST['id'];

			$result_conflict = $this->model_companies->selectDetail(array('comp_id'=>$cust_id));			
			
			if(count($result_conflict)>0){
				if($result_conflict[0]["comp_status"] == -2){
					$this->data["result_conflict"] = $result_conflict[0];

					if(!isset($_GET["cust_conflict"])){
						$paging=0;
					}
					


					// khách hàng chính
					$cust_id = $result_conflict[0]["comp_conflict_id"];
					$result = $this->model_companies->selectDetail(array('comp_id'=>$cust_id));	
					$this->data["result"]=@$result[0];	
					
					//$this->data["set_page"] 	= 'conflict_companies_review';
					//$this->load->view('conflict', $this->data);
                    
                    $this->load->view('qt/conflict_companies_review', $this->data);
				}else{
					$this->load->view('404');
				}
			}else{
				$this->load->view('404');
			}
		}else{
			$this->load->view('404');
		}
	}

	function list_companies($paging=0){
		if($paging<0){
			$paging=0;
		}

		//$array_parent_id =explode("|", $this->session->userdata('parentId'));

		if(isset($_REQUEST["where"])&&$_REQUEST["where"]!=""){
			$where	=$_REQUEST["where"];
		}else{
			$where	='';
		}

		$order_by="cust_create_time ASC";

		$this->data["result"] 	= $this->model_conflict->selectCompanies(array("where"=>$where,"comp_status"=>-2,"order_by"=>$order_by,'limit'=>10,'paging'=>$paging));		
//echo $this->db->last_query();		
		$this->data["count_page"] = $this->model_conflict->selectCountCompanies(array("where"=>$where,"comp_status"=>-2,"order_by"=>$order_by));

	//	print_r($this->data);

	//	$this->data["set_page"] 	= '';
		$this->load->view('qt/conflict_companies_list', $this->data);

	}


	function set_sale_customer(){
		$array = array();
		$user_id = $this->input->post("user_id");
		$user_id_conflict = $this->input->post("user_id_conflict");
		$cust_id = $this->input->post("cust_id");
		$cust_id_conflict = $this->input->post("cust_id_conflict");
		$type = $this->input->post("type");
		// ID này dùng để ID làm gốc mợt lại
		$cust_main_id = $this->input->post("cust_main_id");

		if($user_id==""||$cust_id==""||$cust_main_id==""){
			$ms_array = array("st" =>0,"msg"=>"Thiếu thông tin");
			echo json_encode($ms_array);
			return;
		}

		$result_us = $this->model_conflict->selectCustUser(array("uId"=>$user_id,"cust_id"=>$cust_id));
		//echo $this->db->last_query();
		//print_r($result_us);

		if(count($result_us)<=0){
			$ms_array = array("st" =>0,"msg"=>"Khách hàng này đã được thực thi rồi");
			echo json_encode($ms_array);
			return;
		}

		if($type!=""){
		// Loại bỏ hết type
		$result = $this->model_conflict->selectCustUserFull(array("cust_id"=>$cust_main_id));
			foreach ($result as $key => $value) {
				$ar = json_decode($value["line_prefix"],true);
				if(count($ar)>0){
					foreach($ar as $k =>$v){
						if($type==$v){
							unset($ar[$k]);
						}
					}
				}
				
			//	print_r($ar);
				// Update toàn bộ value
				$this->model_conflict->updateCustUser(array("line_prefix"=>json_encode($ar)),array("uId"=>$value["uId"],"cust_id"=>$value["cust_id"]));
			}
		}


	

		
		//print_r($result);
		if(@$result_us["line_prefix"]!=""){
			$array = json_decode($result_us["line_prefix"]);			
		}
		
		// SELECT TẤT CẢ THUỘC LOẠI CHÍNH
		if(count($array)>0){
			if(!in_array($type, $array)){
				array_push($array,$type);
			}
		}else{
			array_push($array,$type);
		}
		
		$id_chones = $user_id;
		$this->model_conflict->updateCustUser(array("line_prefix"=>json_encode($array),"cust_id"=>$cust_main_id),array("uId"=>$user_id,"cust_id"=>$cust_id));
		// BÍ QUÁ SỬ LÝ BÙA
		if($cust_id!=$cust_id_conflict){
			$this->model_customer->updateConflict(array("cust_creator_id"=>-1),$cust_id_conflict,"");
			//echo "vao";
		}else{
		//echo "vao1";
			$this->model_customer->updateConflict(array("cust_creator_id"=>-1),$cust_id,$cust_main_id);
		}
		
		//echo $this->db->last_query();
		if($user_id_conflict!=""){
			$this->model_conflict->updateCustUser(array("cust_id"=>$cust_main_id),array("uId"=>$user_id_conflict,"cust_id"=>$cust_id_conflict));
			$this->model_customer->updateConflict(array("cust_creator_id"=>-1),$cust_id_conflict,"");
			$id_chones = $user_id_conflict;
		}
		
		// Lay trong bang feet_cust_user
		$result = $this->model_conflict->selectOrder(array("array_cust_id"=>array($cust_id_conflict,$cust_main_id)));
//	echo "test";
	//	echo $cust_main_id;
//echo $this->db->last_query();
		if(count($result)>0){
			foreach($result as $v){
				$order_id = $v["order_id"];
				$r = file_get_contents("http://localhost/quanlyled/supersale/api/php_api.php?token=".$this->session->userdata('user_token')."&id_order=".$order_id."&sale_id=".$id_chones);
				//echo "http://localhost/quanlyled/supersale/api/php_api.php?token=".$this->session->userdata('user_token')."&id_order=".$order_id."&sale_id=".$id_chones;
				//print_r($r);
				
				$this->model_conflict->deleteConflict(array("order_id"=>$order_id));
				
			}
		}else{
		
		}
		//exit();
		//$this->model_conflict->deleteConflict(array("cust_id"=>$cust_id_conflict,"type"=>$type));

		$this->model_feeds->updateCustID(array("feed_cust_id"=>$cust_id),$cust_id_conflict,'');
		

		$ms_array = array("st" =>1,"redirect"=>base_url("customer/detail?id=".$cust_main_id),"msg"=>"Set thành công");
		echo json_encode($ms_array);
	}
}

